#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <openssl/md5.h>

#include "dict.h"

/*
 * char_in_dict, check if a character is in dict
 */
extern int char_in_dict(const char* dict, int dict_length, char character);

/*
 * index_in_dict, get index number of character in dict
 */
extern int index_in_dict(const char* dict, int dict_length, char character);

struct dict_set normal = {
	.year_dict = {'2', '5', '8', 'B', 'E', 'H', 'L', 'P', 'S', 'V', 'Y', '3', '6', '9', 'C'},
	.yday_dict = {'3', '8', 'D', 'J', 'P', 'U', 'Z', '6', 'B', 'G', 'M', 'S', 'X', '4', '9', 'E', 'K', 'Q', 'V', '2'},
	.dict = {'2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'},
	.dict_type = NORMAL_DICT
};

/*
 * char_in_dict, check if a character is in dict
 */
inline int char_in_dict(const char* dict, int dict_length, char character)
{
        int i;
        for(i = 0; i < dict_length; ++i)
        {
                if(dict[i] == character)
		{
                        return 1;
		}
        }

        return 0;
}

/*
 * index_in_dict, get index number of character in dict
 */
inline int index_in_dict(const char* dict, int dict_length, char character)
{
        int index;
        for(index = 0; index < dict_length; index++)
        {
                if(dict[index] == character)
                        return index;
        }
        return 100;
}

/*
 * string_count_char_in_dict, get number of character which is both in str and dict
 */
int string_count_char_in_dict(const char* str, const char* dict, int dict_length)
{
	int count = 0;
	char* p;
	p = (char*)str;


	while(*p != '\0')
	{
		if(char_in_dict(dict, dict_length, *p))
			count++;
		p++;
	}

	return count;
}


static const char code_dict[] = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9',
};

/*
 * _hid_to_code, get code from hid
 */
void _hid_to_code(const char* hid, char code[8])
{
	unsigned char md[MD5_DIGEST_LENGTH];
	MD5_CTX ctx;
	int i;
	memset(md, 0, MD5_DIGEST_LENGTH);

	MD5_Init(&ctx);
	MD5_Update(&ctx, hid, strlen(hid));
	MD5_Final(md, &ctx);

	for(i = 0; i < 8; ++i)
	{
		code[i] = code_dict[((int)md[i] + (int)md[i + 8]) % sizeof(code_dict)];
	}
}

